<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
                <!-- <el-form-item label="上级流程" prop="pid" v-if="formData.pid !== 0 && mode.value=='add'">
                    <el-tree-select class="flex-1" v-model="formData.pid" :data="optionsData.dept" clearable
                        node-key="id" :props="{
            value: 'id',
            label: 'name'
        }" check-strictly :default-expand-all="true" placeholder="请选择上级流程" />
                </el-form-item> -->
                <el-form-item label="流程名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入流程名称" :maxlength="100" />
                </el-form-item>
                <el-form-item if="formData.pid !== 0 " label=" 审批模式" prop="flowtype">
                    <el-radio-group v-model="formData.flowtype" class="ml-4">
                        <el-radio :label="1">并行审批</el-radio>
                        <el-radio :label="2">同时审批</el-radio>
                    </el-radio-group>
                    <div class="form-tips">并行审批：一个审批人通过，则进入下一环节。同时审批：所有审批人通过，则进入下一环节</div>
                </el-form-item>
                <!-- @select="deptUserSelect" -->
                <!-- <el-form-item label="流程领导" prop="leader"> -->
                <!-- <el-autocomplete :fetch-suggestions="querySearch" placeholder="搜索姓名" :trigger-on-focus="false"
                        v-model="deptData.realname">

                        <template #prepend>
                            <el-select v-model="deptData.levelid" placeholder="选择级别" :maxlength="80">
                                <el-option label="上级主管" value="1" />
                                <el-option label="流程主管" value="2" />
                            </el-select>
                        </template>
<template #append>
                            <el-button type="primary" @click="deptUserAdd">添加</el-button>
                        </template>
</el-autocomplete> -->


                <!-- <el-input
                        v-model="formData.leader"
                        placeholder="请输入负责人姓名"
                        :maxlength="30"
                    /> -->
                <!-- </el-form-item> -->
                <!-- <el-form-item v-for="item in formData.deptUser" :key="item.id">

                    <el-col :span="8">{{ item.level }}</el-col>
                    <el-col :span="8">{{ item.realname }}</el-col>
                    <el-col :span="8"><el-button type="primary" @click="deptUserDel">删除</el-button></el-col>

                </el-form-item> -->
                <!-- <el-form-item label="联系电话" prop="mobile">
                    <el-input v-model="formData.mobile" placeholder="请输入联系电话" />
                </el-form-item> -->
                <el-form-item label="审批顺序" prop="sort">
                    <div>
                        <el-input-number v-model="formData.sort" :min="0" :max="9999" />
                        <div class="form-tips">默认为0， 审批顺序由大到小</div>
                    </div>
                </el-form-item>
                <!--  <el-form-item label="流程状态">
                    <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
                </el-form-item> -->
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { flowEdit, flowAdd, flowDetail, flowAll, flowSearchUser } from '@/api/org/flow'
import Popup from '@/components/popup/index.vue'
import { useDictOptions } from '@/hooks/useDictOptions'
import request from '@/utils/request'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑流程' : '新增流程'
})
/**添加流程领导 */
const deptData = reactive({
    deptid: 0,
    levelid: '',
    realname: ''
})
/**处理用户选择 */
interface LinkItem {
    value: string
    name: string
}
const Userlinks = ref<LinkItem[]>([])
/**添加流程用户 */
const deptUserAdd = () => {
    formData.deptUser = request.post({ url: '/dept.dept/deptuseradd?deptid=' + formData.id + '&levelid=' + deptData.levelid + '&realname=' + deptData.realname })

    console.log('Selected item:', formData.deptUser);
}
/**删除流程用户 */
const deptUserDel = (item: any) => {
    console.log('Selected item:', item);
}
// 远程获取补全内容的函数
let timeout: ReturnType<typeof setTimeout>
const querySearch = async (queryString: string, cb: any) => {
    // Userlinks.value = await deptSearchUser(queryString)
    // console.log('返回查询用户', Userlinks.value)

    // clearTimeout(timeout)
    // timeout = setTimeout(() => {
    //     cb(Userlinks.value)
    // }, 3000 * Math.random())

    // 模拟发送 AJAX 请求
    // setTimeout(() => {
    //     // 这里模拟一个假数据，实际上应该发送请求到远程服务器
    //     const results = ['张山', '李四', '张二', '王司马子', '来来来']
    //         .filter(item => item.toLowerCase().includes(queryString.toLowerCase()));
    //     cb(results);
    // }, 300); // 模拟延迟
};
const formData = reactive({
    id: '',
    pid: 0 as string | number,
    name: '',
    leader: '',
    flowtype: 1,
    sort: 0,
    deptUser: [] as any,
    status: 1
})


const formRules = {
    // pid: [
    //     {
    //         required: true,
    //         message: '请选择上级流程',
    //         trigger: ['change']
    //     }
    // ],
    name: [
        {
            required: true,
            message: '请输入流程名称',
            trigger: ['blur']
        }
    ]
}

const { optionsData } = useDictOptions<{
    dept: any[]
}>({
    dept: {
        api: flowAll
    }
})

const handleSubmit = async () => {
    await formRef.value?.validate()
    mode.value == 'edit' ? await flowEdit(formData) : await flowAdd(formData)
    popupRef.value?.close()
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await flowDetail({
        id: row.id
    })
    setFormData(data)
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
